<?php
/* --------------------------------------------------------------
   add_sso_cookie_consent_purpose.php 2023-10-27
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2023 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/

/** @var DatabaseModel $this */
/** @var int $t_success */

// If the SSO module is not installed, we skip
// The purpose will be added once the module is installed
$ssoModule = $this->query("SELECT `value` FROM `gx_configurations` WHERE `key` LIKE '%MODULE_CENTER_SINGLESIGNON_INSTALLED%';", true);

if ($ssoModule->num_rows === 0) {
    return;
}

$value = $ssoModule->fetch_assoc()['value'] ?? 0;
$isInstalled = (int)$value === 1;

if ($isInstalled === false) {
    return;
}

// If the module is installed, we check if the purpose is already in the database
// If not, we insert the purpose
$ssoCookiePurpose = $this->query("SELECT * FROM cookie_consent_panel_purposes WHERE purpose_alias = 'gambio/singleSignOn';");

if (!$ssoCookiePurpose) {
    $shopLanguages = $this->getLanguages();
    
    if ($shopLanguages) {
        $lastPurposeId = $this->query("SELECT purpose_id FROM cookie_consent_panel_purposes ORDER BY purpose_id DESC LIMIT 1", true);
        $lastPurposeId = (int)$lastPurposeId->fetch_assoc()['purpose_id'] + 1;
        
        $values = '';
        foreach ($shopLanguages as $language) {
            $values .= "({$lastPurposeId}, {$language['languages_id']}, 2, '', 'SingleSignOn', 'gambio/singleSignOn', 0, 0),";
        }
        
        if ($values) {
            $values = rtrim($values, ',');
            $insertQuery = "INSERT INTO `cookie_consent_panel_purposes`
                                (purpose_id, language_id, category_id, purpose_description, purpose_name, purpose_alias, purpose_status, purpose_deletable)
                                VALUES
                                {$values};
                            ";
            $t_success &= $this->query($insertQuery, true);
        }
    }
}